import AuthComponent from '@/components/Authorized/AuthComponent';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, message, DatePicker, Radio, Modal,Input,Select} from 'antd';
import React, { useState, useCallback, useRef, useEffect } from 'react';
import ProTable from '@ant-design/pro-table';
import ListofDetails from './components/ListofDetails';
import Addexcel from './components/Addexcel'
import { useRequest } from '@umijs/hooks';
import router from 'umi/router'
import { queryluggageTable, accidentlistClosed, importFun, exportChart,queryCityInfo } from './service';
import moment from 'moment';
import styles from './index.less';
const { Option } = Select;
const { confirm } = Modal
// let hiddenData = null;
const TableList = (props) => {
   const { location: {state} } = props;
  //  console.log(props)
  // 到达航站，出发航站搜索数据
  const { data: selectData } = useRequest(queryCityInfo);
  // 详情模态框
  const [createModalVisible, handleModalVisible] = useState(false);
  // 上传模态框
  const [AddExcelModalVisible, handleAddExcel] = useState(false);
  // 储存搜索条件
  const [saveSearchData, handleSearchData] = useState({});
  const [height, controlH] = useState(300);

  const [isCollapse, controlC] = useState(true);
  useEffect(() => {
    if (isCollapse) {
      controlH(document.body.clientHeight - 360);
    } else {
      controlH(document.body.clientHeight - 530);
    }
  }, [isCollapse])

  const [exportFlag, handleExportFlag] = useState('')//导出数据
  const searchRef = useRef();
  const reloadTable = useCallback(function reloadData() {
    if (searchRef.current) {
      searchRef.current.click();
    }
  }, []);

  const formatFlightNo = (val) => {
    if (!val) {
      return '';
    } else if (val.length < 3 || /^\D/.test(val)) {
      return ''.toUpperCase.call(val);
    } else if (/^\d{2}/.test(val)) {
      return `3U${val}`;
    } else {
      return val;
    }
  }

  const [accidentId, setaccidentId] = useState('0');
  //分解
  const actionRef = useRef();
  const ref = useRef();
  const [dataScope, setDataScope] = useState('0');
  const onScopeChange = useCallback(e => {
    setDataScope(e.target.value);
    handleSelectedRowKeys([])
  }, []);
  const [selfPramas, setSelfPramas] = useState({})
  const [inited, setInited] = useState(false)
 // 第一次加载
 const [firstLoadDate, setFirstLoadDate] = useState(true)
  useEffect(() => {
    if (actionRef.current && inited) {
      reloadTable();
     } else {
      setInited(true)
    }
  },[dataScope, inited, selfPramas])

  // 从消息页跳转过来，初始化加载查询参数
  useEffect(()=>{
    if (ref.current && state && sessionStorage.getItem('firstLoad')){
      // console.log(state.accidentId);
      setDataScope('')
      ref.current.setFieldsValue({
        startDate: state.flightDate ? moment(state.flightDate) : '',
        endDate: state.flightDate ? moment(state.flightDate) : '',
        flightNo: state.flightNo ? state.flightNo : '',
        accidentId: state.accidentId ? state.accidentId : '',
      })
      reloadTable();
      sessionStorage.removeItem('firstLoad')
    }
  }, [ref.current])

  // 点击到详情的方法，顺便传值 id 过去
  const toDdetails=useCallback(e => {
    handleModalVisible(true)
    }, []);
  // 切换清空搜索
//   useEffect(() => {
//     hiddenData = null
//   // eslint-disable-next-line react-hooks/exhaustive-deps
//   }, [])
  const beforeSearchSubmit = useCallback(params => {
    params['startDate'] = params.startDate ? params.startDate.format('YYYY-MM-DD') : '';
    params['endDate'] = params.endDate ? params.endDate.format('YYYY-MM-DD') : '';

    if (!isCollapse) {
      return { ...params, dataScope }
    } else {
       if (event&&event.target&&event.target.querySelector&&event.target.querySelector('span') && event.target.querySelector('span').innerText === '查 询') {
        if (Object.keys(params).indexOf('startDate') === -1) {
          params.startDate = ''
        }
        if (Object.keys(params).indexOf('endDate') === -1) {
          params.endDate = ''
        }
      } else if (event&&event.target&&event.target.querySelector&&event.target.querySelector('span') && event.target.querySelector('span').innerText === '重 置') {
        ref.current.setFieldsValue({
          startDate: moment(),
          endDate: moment()
        })
        // hiddenData = {}
      }
      // return { ...hiddenData, ...params, dataScope }
      return { ...params, dataScope }
    }
  }, [dataScope]);

  const [selectedRowKeys, handleSelectedRowKeys] = useState([]) // 勾选索引
  const [selectedRows, handleSelectedRows] = useState([]) // 勾选列
  // 选中添加值
  const tableSelectChange = (selectedRowKeys, selectedRows) =>{
    handleSelectedRowKeys(selectedRowKeys)
    handleSelectedRows(selectedRows)
  }
  // 设置选中的值
  const rowSelection = {
    selectedRowKeys,
    onChange: tableSelectChange,
  };

  //事故结案方法
  const handleAccidentlistClosed = async (selectedRows) => {
    if (selectedRows && selectedRows.length > 0) {
      try {
        await accidentlistClosed({
          accidentId: selectedRows.map(row => row.accidentId)
        })
        message.success('结案成功，即将刷新');
        return true;
      } catch (error) {
        message.error('结案失败，请重试');
        return false;
      }
    } else {
      message.error('请选择条目')
    }
  };
  //行李匹配方法
  const handleMatchingLuggage = async (selectedRows) => {
  if (selectedRows && selectedRows.length > 0) {
      if (selectedRows.map(row => row.accidentType)[0]==='少收行李') {
         setDataScope('')
          ref.current.setFieldsValue({
          startDate:'',
          endDate: '',
          status:'0',
          accidentType:'3',
          pkgNo: selectedRows.map(row => row.pkgNo)[0],
         })
         reloadTable()
      }
      if (selectedRows.map(row => row.accidentType)[0]==='多收行李') {
         setDataScope('')
         ref.current.setFieldsValue({
          startDate:'',
          endDate: '',
          status:'0',
          accidentType:'2',
          pkgNo: selectedRows.map(row => row.pkgNo)[0],
         })
         reloadTable()
      }
      message.success('行李匹配结果为表格所示，空表格为无相似数据');
    //   if (exportFlag===true){
    //    message.error('无相似数据')
    //   }else{
    //    message.success('行李匹配成功，即将刷新');
    //  }
  } else {
        message.success('行李匹配失败');
  }
  };
  // 导入
  const exportAdd =useCallback(e => {
    handleAddExcel(true)
  }, []);

  // 导出报表
  const exportCharts = () => {
    if (!exportFlag){
      message.error('表格数据为空')
      return false
    }
    const hide = message.loading('正在导出');
    let res =exportChart(saveSearchData).then(res=>{
      let blob = new Blob([res], {
        type: 'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      })
      let elink = document.createElement('a')
      let time=moment(Date.now()).format('YYYY-MM-DD HH_ss_mm')
      elink.download = '异常行李列表'+time+'.xls'
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      document.body.removeChild(elink)
      hide();
      message.success('导出成功');
    }).catch(err => {
      console.log(err)
    });
  }
  const columns = [
    {
      title: '事故单号',
      dataIndex: 'accidentId',
      width: 100,
      order: 10,
      renderFormItem: (_, { defaultRender, ...rest }) => {
        return <Input onChange={e => {
          e.target.value = e.target.value.toUpperCase()
        }} {...rest} maxLength={20} placeholder="请输入" style={{'text-transform':'uppercase'}}/>
      }
    },
    {
      title: '类型',
      key: 'accidentType',
      initialValue: '',
      dataIndex: 'accidentType',
      width: 100,
      filters: [
        {text: '破损行李', value: '破损行李'},
        {text: '少收行李',value: '少收行李'},
        {text: '多收行李',value: '多收行李'},
        {text: '内件缺失行李',value: '内件缺失行李'}
      ],
      valueEnum: {
        '': '全部',
        '1': '破损行李',
        '2': '少收行李',
        '3': '多收行李',
        '4': '内件缺失行李'
      },
    },
    {
      title: '状态',
      key: 'status',
      dataIndex: 'status',
      initialValue: '0',
      width: 100,
      filters: [
        {text: '处理中',value: '处理中'},
        {text: '已结案', value: '已结案'}
      ],
      valueEnum: {
        '': '全部',
        '0': '处理中',
        '1': '已结案',
      },
    },
    {
      title: '补偿单数量',
      dataIndex: 'payCount',
      width: 120,
      hideInSearch: true
    },
    {
      title: '补偿总额',
      dataIndex: 'totalPay',
      width: 100,
      hideInSearch: true
    },
    {
      title: '航班日期',
      width:100,
      dataIndex: 'flightDate',
      hideInSearch: true
    },
    {
      title: '航班开始日期',
      hideInTable: true,
      dataIndex: 'startDate',
      order: 12,
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{width: '100%'}}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '航班结束日期',
      hideInTable: true,
      order: 11,
      dataIndex: 'endDate',
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{width: '100%'}}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '航班号',
      dataIndex: 'flightNo',
      width: 100,
      order: 9,
      renderFormItem: (_, { type, defaultRender, ...rest }) => {
        return <Input
          {...rest}
          onChange= {e => {
            e.target.value = formatFlightNo(e.target.value);
            rest.onChange(e.target.value)
          }}
          allowClear maxLength={6} placeholder="3U" />;
      }
    },
    {
      title: '补偿类型',
      key: 'compensateType',
      hideInTable: true,
      dataIndex: 'compensateType',
      initialValue: '',
      width: 100,
      filters: [
        {text: '行李箱',value: '0'},
        {text: '现金', value: '1'},
        {text: '行李箱+现金', value: '2'},
      ],
      valueEnum: {
        '': '全部',
        '0': '行李箱',
        '1': '现金',
        '2':'行李箱+现金'
      },
    },
    // {
    //   title: '补偿单状态',
    //   key: 'orderStatus',
    //   dataIndex: 'orderStatus',
    //   initialValue: '',
    //   hideInTable: true,
    //   width: 100,
    //   valueEnum: {
    //     '': '全部',
    //     1: '待审核',
    //     2: '通过',
    //     3: '生效',
    //     4: '关闭',
    //     5: '未通过',
    //   },
    // },
    {
      title: '旅客搜索',//支持旅客姓名、行李号
      hideInTable: true,
      dataIndex: 'keySearch',
      width: 100
    },
    {
      // 多个查询选项
      title: '服务航站',
      dataIndex: 'serviceCity',
      initialValue: '',
      width: 100,
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder='请选择'
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            {...rest}
          >
            {
              selectData&&selectData.map((v,i) => {
                return (
                  <Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>
                )
              })
            }
          </Select>
        );
      }
    },
    // {
    //   title: '服务航站',
    //   dataIndex: 'serviceCity',
    //   initialValue: '',
    //   width: 100,
    //   renderFormItem: (item, { ...rest }) => {
    //     return (
    //       <Select
    //         showSearch
    //         placeholder="请选择"
    //         defaultActiveFirstOption={false}
    //         showArrow={false}
    //         filterOption={true}
    //         notFoundContent={null}
    //         {...rest}
    //       >
    //         {selectData &&
    //           selectData.map((v, i) => {
    //             return <Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>;
    //           })}
    //       </Select>
    //     );
    //   },
    // },
    {
      title: '航段',
      dataIndex: 'segment',
      width: 100,
      hideInSearch: true
    },
    {
      title: '旅客姓名',
      dataIndex: 'paxName',
      width: 100,
      hideInSearch: true
    },
    {
      title: '行李号',
      dataIndex: 'pkgNo',
      width: 100,
      renderFormItem: (_, { defaultRender, ...rest }) => {
        return <Input onChange={e => {
          e.target.value = e.target.value.toUpperCase()
        }} {...rest} maxLength={20} placeholder="请输入" style={{'text-transform':'uppercase'}}/>
        }
    },
    {
      title: '旅客地址',
      dataIndex: 'postAddr',
      width: 150,
      hideInSearch: true
    },
    // {
    //   title: '领取状态',
    //   dataIndex: 'receiveStatus',
    //   initialValue: '',
    //   hideInTable: true,
    //   width: 100,
    //   valueEnum: {
    //     '': '全部',
    //     0: '未领取',
    //     1: '已领取',
    //     2: '处理中',
    //     3: '已逾期',
    //   },
    // },
    {
      title: '尺寸',
      dataIndex: 'pkgSize',
      width: 100,
      hideInSearch: true
    },
    {
      title: '数据导入',
      dataIndex: 'dataType',
      width: 100,
      hideInSearch: true
    },
    {
      title: '创建人',
      dataIndex: 'createUser',
      width: 100,
      hideInSearch: true
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 100,
      hideInSearch: true
    }
  ];
  return (
    <div id="lugageIndexId" style={{position:"relative"}}>
      <ProTable
        scroll={{ x: 1100, y: height }}
        className={`${styles.luggageTable} rest-pro-table-form-compact ${isCollapse?'':'collapse'}`}
        options={{density: false,fullScreen:true, reload:false, setting:true}}
        size='small'
        headerTitle={
          <div>
            <span style={{ paddingRight: 10, fontWeight: "bold", color: "#000" }}>异常行李列表</span>
            <Radio.Group buttonStyle="solid" defaultValue={dataScope} value={dataScope} onChange={onScopeChange}>
              <Radio.Button value="">全部</Radio.Button>
              <Radio.Button value="0">我发起的</Radio.Button>
              <Radio.Button value="1">草稿</Radio.Button>
            </Radio.Group>
          </div>
        }
        actionRef={actionRef}
        formRef={ref}
        toolBarRender={() => [
          <AuthComponent authCode="luggage.index.pkgCase">
            <Button
              icon='slack'
              type="primary"
              style={{ padding: '0px 0px 0px 8px',width:'100px' }}
              onClick={() => {
                if (selectedRowKeys.length === 0) {
                  message.error("请选择事故结案的条目")
                } else {
                  confirm({
                    title: '提示',
                    content: '确认操作后，事故单状态变为【已结案】，你还要继续吗？',
                    onOk: async () => {
                      await handleAccidentlistClosed(selectedRows);
                      handleSelectedRowKeys([])
                      if (actionRef.current) {
                        actionRef.current.reload();
                      }
                    },
                    onCancel() { }
                  })
                }
              }}
              selectedKeys={[]}
            >
              事故结案
            </Button>
        </AuthComponent>,
        <AuthComponent authCode="luggage.index.pkgMatch">
          <Button
            icon='fullscreen'
            style={{ padding: '0px 0px 0px 8px',width:'100px' }}
            onClick={() => {
              if (selectedRowKeys.length === 0||selectedRowKeys.length > 1||(selectedRows[0].accidentType!=='少收行李'&&selectedRows[0].accidentType!=='多收行李')) {
                message.error("只能选择一条 少收行李 或 多收行李 进行匹配的条目")
              } else {
                confirm({
                  title: '提示',
                  content: '确认操作后，异常行李将进行匹配，你还要继续吗？',
                  onOk: async () => {
                    await handleMatchingLuggage(selectedRows);
                    handleSelectedRowKeys([])
                  },
                  onCancel() { }
                })
              }
            }}
            selectedKeys={[]}
          >
            行李匹配
          </Button >
        </AuthComponent>,
        <AuthComponent authCode="luggage.index.import">
          <Button onClick={() => exportAdd()} icon="upload" type="primary" style={{ padding: '0px 0px 0px 8px',width:'73px' }}>
            导入
          </Button>
        </AuthComponent>,
        <AuthComponent authCode="luggage.index.export">
          <Button onClick={() => exportCharts()} icon="download" type="primary" style={{ padding: '0px 0px 0px 8px',width:'73px' }}>
            导出
          </Button>
        </AuthComponent>
        ]}
        search={{
          searchText: (
            <span ref={searchRef} href>
              查询
            </span>
          ),
          onCollapse: val => {
            controlC(val);
            // if (!val && hiddenData) {
            //   ref.current.setFieldsValue({
            //     status: hiddenData.status,
            //     accidentType: hiddenData.accidentType,
            //     accidentId: hiddenData.accidentId,
            //     compensateType: hiddenData.compensateType,
            //     orderStatus: hiddenData.orderStatus,
            //     keySearch: hiddenData.keySearch,
            //     serviceCity: hiddenData.serviceCity,
            //     receiveStatus: hiddenData.receiveStatus,
            //   })
            // } else {
            //   hiddenData = ref.current.getFieldsValue()
            // }
          }
        }}
        request={params => {
          dataScope ? params['queryType'] = dataScope : 0;
          if (!params['startDate'] && !params['endDate']) {
            params['startDate'] = moment().format('YYYY-MM-DD');
            params['endDate'] = moment().format('YYYY-MM-DD');
            ref.current.setFieldsValue({
              startDate: moment()
            })
            ref.current.setFieldsValue({
              endDate: moment()
            })
          }
          if (!params['accidentType']) {
            ref.current.setFieldsValue({
              accidentType: ''
            })
          }
          if (!params['compensateType']) {
            ref.current.setFieldsValue({
              compensateType: ''
            })
          }
          if (!params['status']) {
            ref.current.setFieldsValue({
              status: ''
            })
          }
          handleSearchData({...params, ...selfPramas})
          return queryluggageTable({...params, ...selfPramas})
        }}
        postData={data => {
          if (data.length === 0) {
            handleExportFlag(false)
          } else {
            handleExportFlag(true)
          }
          return data
        }}
        beforeSearchSubmit={beforeSearchSubmit}
        onRow={record => {
					return {
						onClick: () => {
              if(AuthComponent.getAuth('luggage.index.detail')){
              setaccidentId(record.accidentId)
              toDdetails()
						}}
					}
				}}
        columns={columns}
        rowSelection={
          (AuthComponent.getAuth('luggage.index.pkgCase') ||
          AuthComponent.getAuth('luggage.index.pkgMatch'))
          ? rowSelection
          : false
        }
        rowKey='accidentId'
         pagination={{
          showSizeChanger: true,
          showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 项`
        }}
      />
      {createModalVisible && <ListofDetails
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
        accidentId={accidentId}
      />}
       <Addexcel
        onCancel={() => handleAddExcel(false)}
        addExcel={AddExcelModalVisible}
      />
    </div>
  );
};

export default Form.create()(TableList);
